from counterpoint.decorators import forum_staff_required
from counterpoint.forms.admin import ForumGroupForm, ForumForm
from counterpoint.forms.admin import GroupOrderingForm, ForumOrderingForm
from counterpoint.helpers import render_response
from counterpoint.models import Forum, ForumGroup
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404
from django.views.generic import list_detail


# TODO: update for formsets

try:
    all
except NameError:
    def all(items):
        import operator
        return reduce(operator.and_, [bool(item) for item in items])


def forumgroup_add_edit(request, group_id=None):
    group = ForumGroup()
    if group_id:
        group = get_object_or_404(ForumGroup, pk=group_id)
    if request.method == 'POST':
        form = ForumGroupForm(request.POST, instance=group)
        if form.is_valid():
            form.save()
            request.user.message_set.create(message="Forum Group created.")
            return HttpResponseRedirect(reverse('cp_admin_forum_list'))
    else:
        if group_id:
            form = ForumGroupForm(instance=group)
        else:
            o = ForumGroup.objects.order_by('-ordering')[0].ordering + 1
            form = ForumGroupForm(initial={'ordering': o})
    return render_response(request,
                           'counterpoint/admin/forumgroup/add_edit.html',
                           {'form': form, 'group': group})

forumgroup_add_edit = forum_staff_required(forumgroup_add_edit)


def forum_add_edit(request, group_id, forum_id=None):
    group = get_object_or_404(ForumGroup, pk=group_id)
    forum = Forum()
    if forum_id:
        forum = get_object_or_404(Forum, pk=forum_id)
    if request.method == 'POST':
        form = ForumForm(request.POST, instance=forum)
        if form.is_valid():
            new_forum = form.save(commit=False)
            new_forum.parent_group = group
            new_forum.save()
            request.user.message_set.create(message="Forum created.")
            return HttpResponseRedirect(reverse('cp_admin_forum_list'))
    else:
        if forum_id:
            form = ForumForm(instance=forum)
        else:
            o = group.forums.order_by('-ordering')[0].ordering + 1
            form = ForumForm(initial={'ordering': o})
    return render_response(request,
                           'counterpoint/admin/forum/add_edit.html',
                           {'form': form, 'forum': forum})

forum_add_edit = forum_staff_required(forum_add_edit)


def forum_list(request):
    forums = Forum.objects.all()
    if request.method == "POST":
        group_ids = Forum.objects.values_list('parent_group_id', flat=True)
        groups = ForumGroup.objects.filter(id__in=group_ids)

        group_forms = []
        for group in groups:
            group_forms.append(GroupOrderingForm(request.POST,
                                                 instance=group,
                                                 prefix='group_%d' % group.id))
        group_forms_valid = all([f.is_valid() for f in group_forms])

        forum_forms = []
        for forum in forums:
            forum_forms.append(ForumOrderingForm(request.POST,
                                                 instance=forum,
                                                 prefix='forum_%d' % forum.id))
        forum_forms_valid = all([f.is_valid() for f in forum_forms])

        if group_forms_valid and forum_forms_valid:
            for form in group_forms:
                form.save()
            for form in forum_forms:
                form.save()
        return HttpResponseRedirect(reverse('cp_admin_forum_list'))

    kwargs = {
        'queryset': forums,
        'allow_empty': True,
        'template_name': 'counterpoint/admin/index.html',
    }
    return list_detail.object_list(request, **kwargs)

forum_list = forum_staff_required(forum_list)
